package com.yao.project.exception;

import com.yao.project.common.BaseResponse;
import com.yao.project.common.ErrorCode;
import com.yao.project.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author yaozy
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private HttpServletRequest request;

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> handlerBusinessException(BusinessException e) {
        String uri = request.getRequestURI();
        log.error("请求地址: {} , BusinessException 信息: {} ", uri, e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }


    /**
     * Validation 参数校验异常处理
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse<?> handleMethodArgumentNotValidException(Exception e) {
        String uri = request.getRequestURI();
        StringBuilder errorInfo = new StringBuilder();
        BindingResult bindingResult = null;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        }
        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            if (i > 0) {
                errorInfo.append(",");
            }
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
        }
        log.error("请求地址: {} ,参数校验异常捕获信息: {}", uri, errorInfo, e);

        return ResultUtils.error(ErrorCode.PARAMS_ERROR, bindingResult.getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> handlerRuntimeExceptionHandler(RuntimeException e) {
        String uri = request.getRequestURI();
        log.error("请求地址: {} ,系统异常", uri, e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
    }
}
